// Can use module FOREVER to keep this server alive, FOREVER will start server while it get shut down for no reason:
// npm i -g forever 
// forever start webhook.js
const http = require('http');
const process = require('child_process');
const PORT = 1111;

http.createServer((request, response) => {
	if (request.url.search(/deploy\/?$/i) > 0) {
		process.exec('git pull', function(error, stdout, stderr) {
			if (error) {
				response.writeHead(500)
				response.end('Server Internal Error.')
				console.log(`stderr: ${stderr}`);
				throw error
			} else {
				response.writeHead(200)
				response.end('Deploy success.')
			}
			console.log(`stdout: ${stdout}`);
		});
	} else {
		response.writeHead(404);
		response.end('Location not found.');
	}
}).listen(PORT);

console.log(`Server running at http://127.0.0.1:${PORT}`);